import React from 'react'
import { connect } from 'react-redux'
import SearchArea from 'components/search-area'
import { Button, Badge, Modal, message } from 'antd'
import { deepCopy, messages } from "share/common";
import ResizeTable from 'components/resize-table'
import financialService from "../financialService";
import config from "config";
import moment from "moment/moment";
import Control from 'components/control'
import AsyncExport from "components/template/async-export/async-export";

class ExportDownload extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [
        {
          title: messages('common.sequence'/*序号*/), dataIndex: 'index', width: 48, render: (text, record, index) =>
            (this.state.page * 10 + index + 1)
        },
        { title: messages('financial-management.key113')/*批次号*/, dataIndex: 'batchNumber' },
        { title: messages('financial-management.key846')/*分录数量*/, dataIndex: 'journalNumbers', width: 120 },
        { title: messages('financial-management.key847')/*帐套*/, dataIndex: 'setOfBooksName' },
        { title: messages('financial-management.key8')/*创建人工号*/, dataIndex: 'createdByEmployeeId' },
        { title: messages('financial-management.key9')/*创建人姓名*/, dataIndex: 'createdByName' },
        {
          title: messages('common.column.status'/*状态*/), dataIndex: 'status', width: 120, render: value => {
            switch (value) {
              case 1001:
                return <Badge status="default" text={messages('financial-management.key593')/*未生成*/}/>;
              case 1002:
                return <Badge status="processing" text={messages('financial-management.key594')/*生成中*/}/>;
              case 1003:
                return <Badge status="success" text={messages('financial-management.key595')/*已生成*/}/>;
              case 1004:
                return <Badge status="error" text={messages('financial-management.key596')/*生成失败*/}/>;
            }
          }
        },
        {
          title: messages('common.operation'), dataIndex: 'id', width: 300, render: (value, record) => {
            const style = { margin: '0px 10px' };
            const { loginUser } = this.props;
            const { searchParams } = this.state;
            return (
              <div className="batch-operate">
                <AsyncExport
                  title={messages('financial-management.key848')/*生成文件*/}
                  data-control={'entry-information.hidden'}
                  refresh={() => {this.getList()}}
                  style={{ display: 'inline-block' }}
                  codeCheck
                  params={{
                    tenantId: loginUser.tenantId,
                    setOfBooksId: searchParams.setOfBooksId,
                    operatorOid: loginUser.userOID,
                    implName: 'journalBatchDownloadServiceImpl',
                    isAsync: true,
                    otherDownloadMsg: {
                      journalBatchId: record.id
                    }
                  }}
                />
                <Button
                  style={style}
                  disabled={record.status !== 1003}
                  data-control={'entry-information.hidden'}
                  onClick={() => this.downloadBatch(record.attachmentUrl)}
                >{messages('financial-management.key598')/*下载*/}</Button>
                <Button
                  loading={record.deleteLoading}
                  data-control={'entry-information.hidden'}
                  onClick={() => {
                    Modal.confirm({
                      title: messages('financial-management.key599')/*确认删除？*/,
                      content: messages('financial-management.key849')/*删除后，批次内的分录可重新生成批次！*/,
                      onOk: () => this.handleDeleteBatch(record.id),
                    })
                  }}>{messages('common.delete')/*删除*/}</Button>
              </div>
            )
          }
        }
      ],
      data: [],
      loading: false,
      pagination: {
        total: 0
      },
      page: 0,
      searchParams: { setOfBooksId: props.company.setOfBooksId },
      searchForm: [
        {
          type: 'select', id: 'setOfBooksId', label: messages('financial-management.key345')/*账套*/, options: [], method: 'get',
          valueKey: 'id', labelKey: 'setOfBooksName', getParams: {roleType: 'TENANT'},
          getUrl: `${config.baseUrl}/api/setOfBooks/by/tenant`,
          defaultValue: {
            label: props.company.setOfBooksName,
            key: props.company.setOfBooksId
          },
          allowClear: false
        },
        {
          type: 'items', id: 'dateRange',
          items: [
            {type: 'date', id: 'createdDateStart', label: messages('financial-management.key850')/*创建日期从*/},
            {type: 'date', id: 'createdDateEnd', label: messages('financial-management.key851')/*创建日期到*/}
          ]
        }
      ]
    }
  }

  componentDidMount(){
    this.getList();
  }

  getList = () => {
    const { searchParams, page } = this.state;
    const { loginUser } = this.props;
    let temp = deepCopy(searchParams);
    temp.page = page;
    temp.tenantId = loginUser.tenantId;
    temp.operatorId = loginUser.id;
    this.setState({loading: true});
    financialService.getBatchList(temp).then(res => {
      this.setState({
        loading: false,
        data: res.data.rows,
        pagination: {
          total: Number(res.data.total),
          current: page + 1,
          onChange: this.onChangePager,
        }
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading: false});
    })
  };

  onChangePager = page => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  setBtnLoading = (id, type, isLoading) => {
    let { data } = this.state;
    data.map(item => {
      if (item.id === id) {
        item[type] = isLoading
      }
    });
    this.setState({ data })
  };

  downloadBatch = url => {
    window.open(url);
  };

  handleDeleteBatch = id => {
    this.setBtnLoading(id, 'deleteLoading', true);
    financialService.deleteBatch({journalBatchId: id}).then(() => {
      this.setBtnLoading(id, 'deleteLoading', false);
      message.success(messages('common.delete.successful')/*删除成功*/);
      this.getList();
    }).catch(e => {
      this.setBtnLoading(id, 'deleteLoading', false);
      message.error(e.response.data.message);
    })
  };

  clear = () => {
    this.setState({searchParams: {setOfBooksId: this.props.company.setOfBooksId}}, () => {
      this.getList();
    })
  };

  search = values => {
    let temp = deepCopy(values);
    temp.createdDateStart && (temp.createdDateStart = moment(temp.createdDateStart.format('YYYY-MM-DD 00:00:00')).utc());
    temp.createdDateEnd && (temp.createdDateEnd = moment(temp.createdDateEnd.format('YYYY-MM-DD 23:59:59')).utc());
    this.setState({ searchParams: temp },() => {
      this.getList();
    })
  };

  render() {
    const { columns, data, loading, pagination, searchForm } = this.state;
    return (
      <Control>
        <div>
          <SearchArea
            searchForm={searchForm}
            submitHandle={this.search}
            clearHandle={this.clear}
          />
          <div style={{ padding: '10px 0px' }}/>
          <ResizeTable
            rowKey="id"
            columns={columns}
            dataSource={data}
            loading={loading}
            pagination={pagination}
            size="middle"
            bordered
          />
        </div>
      </Control>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    loginUser: state.login.loginUser
  }
}

export default connect(mapStateToProps)(ExportDownload);
